<template>
  <div class="infinite-container">
    <mu-list class="bgwhite">
      <mu-list-item title="姓名">
        <mu-text-field hintTextClass="text-right" hintText="请输入姓名" v-model="form.realName" slot="right" class="mt10" inputClass="text-right" disabled>
        </mu-text-field>
      </mu-list-item>
      <mu-divider></mu-divider>
      <mu-list-item title="证件号码">
        <mu-text-field hintTextClass="text-right" hintText="请输入证件号码" v-model="form.idcard" slot="right" class="mt10" inputClass="text-right" disabled>
        </mu-text-field>
      </mu-list-item>
      <mu-divider></mu-divider>
      <mu-list-item title="认证方式">
          <span class="list-right-title" >
              <selector :options="CARD_TYPE"  @selectchange="handleCardChange" :defaultValue="form.cardType" ></selector>
          </span>
      </mu-list-item>
      <mu-divider/>


      <div v-if="form.cardType === '2'">
          <mu-list-item title="预留手机号" >
          <div slot="right">
            <mu-text-field style="width:100px;" hintTextClass="text-right"  :value="form.mobile | hideMobile" disabled  slot="right" class="mt10" inputClass="text-right">
          </mu-text-field>
            <mu-raised-button class="small no-shadow" :label="vcodeLabel" @click="tipDialog.show = true" secondary :disabled="vcodeDisabled"></mu-raised-button>
          </div>
        </mu-list-item>
        <mu-divider/>
        <mu-list-item title="验证码" >
          <div slot="right">
            <mu-text-field hintTextClass="text-right" hintText="请输入验证码" v-model="vcode" style="width:110px;"  class="mt10" inputClass="text-right">
          </mu-text-field>
          </div>
        </mu-list-item>
        <mu-divider/>
      </div>

      <template v-if="form.cardType === '1'">
        <mu-list-item title="卡类型" >
          <span class="list-right-title" >
           <selector :options="cardList"  @selectchange="handleHisCardChange" :defaultValue="form.cardType" ></selector>
          </span>
        </mu-list-item>
        <mu-divider/>
        <mu-list-item title="卡号" >
          <mu-text-field v-model="form.cardNumber" hintTextClass="text-right" hintText="请输入卡号"  slot="right" inputClass="text-right">
          </mu-text-field>
        </mu-list-item>
        <mu-divider/>
      </template>
    </mu-list>

    <div class="text-right  pd10 f12">
        <router-link to="/lisence" class="t5">如何获取医院预留手机号码或卡号？>></router-link>
    </div>

    <mu-flexbox :gutter="0" style="margin-top:3em;">
      <mu-flexbox-item grow="2"></mu-flexbox-item>
      <mu-flexbox-item grow="16">
        <mu-raised-button class="submit-btn" label="确定" @click="addcard" fullWidth primary v-if="form.cardType === '1'"></mu-raised-button>
         <mu-raised-button class="submit-btn" label="确定" @click="checkCode" fullWidth primary v-if="form.cardType === '2'"></mu-raised-button>
      </mu-flexbox-item>
      <mu-flexbox-item grow="2"></mu-flexbox-item>
    </mu-flexbox>

   <!-- confirm dialog -->
    <mu-dialog :open="selectCardDialog" title="请选择需要绑定的卡片(可多选)">
      <div class="">
        <div class="cards-wrapper">
            <mu-list>
              <mu-list-item :describeText="v.patientMedicalCardNumber" v-for="(v, i) in listMedicalCard" :key="i" >
                <div slot="title">
                  {{HIS_CARD_TYPE[v.patientMedicalCardType]}} &nbsp; <small class="t5">{{v.patientNature}}</small>
                </div>
                <div slot="right">
                   <mu-checkbox :nativeValue="v.patientMedicalCardNumber" v-model="checklist" />
                </div>
              </mu-list-item>
            </mu-list>
        </div>
      </div>
      <mu-flat-button slot="actions" @click="selectCardDialog=false" label="取消" />
      <mu-flat-button slot="actions" primary @click="addMultiCard" label="确定" :disabled="checklist.length === 0"/>
    </mu-dialog>

    <div class="pd10 t3 f12" style="padding:1em 30px;" v-if="form.cardType === '1'">
      <div>温馨提示：</div>
      <ul>
        <li v-for="(item, index) in BIND_CARD_TIPS" :key="index">{{index+1}}.{{item}}</li>
      </ul>
    </div>

    <div class="pd10 t3 f12" style="padding:1em 30px;" v-else>
      <div>温馨提示：</div>
      <ul>
        <li v-for="(item, index) in BIND_CARD_TIPS2" :key="index">{{index+1}}.{{item}}</li>
      </ul>
    </div>

    <mu-dialog :open = "tipDialog.show">
      <div class="">我们将对该就诊人在医院建档预留的手机号<span class="t5">{{query.mobile|hideMobile}}</span>发送验证码，如确认该手机号为在用号码，可获取验证码进行身份认证，如已更换号码，请至<span class="t5">医院窗口</span>修改预留手机号。</div>
      <mu-flat-button slot="actions"  @click="tipDialog.show=false" label="取消"/>
      <mu-flat-button slot="actions" primary @click="getVcode" label="确定"/>
    </mu-dialog>

    <mu-dialog :open="firstComeDialog">
      <div class="center">就诊人是否首次到我院就诊（无本院就诊卡）</div>
      <div class="login center mt20">
        <mu-flat-button slot="actions" primary @click="firstConfirm" label="是"/>
        <mu-flat-button slot="actions"  @click="firstComeDialog=false" label="否"/>
      </div>
    </mu-dialog>

    <mu-dialog :open="successDialog">
      <div class="center">认证成功！请凭门诊号到医院自助机或窗口进行办卡就诊。</div>
      <div class="login center mt20">
        <mu-flat-button slot="actions" primary @click="successConfirm" label="确定"/>
      </div>
    </mu-dialog>

    <!--  dialogMobiles -->
    <mu-dialog :open="dialogMobiles" title="请选择手机号">
      <div class>
        <div class="cards-wrapper">
          <mu-list>
            <mu-list-item
              v-for="(v, i) in mobilesList"
              :key="i"
              @click.native="mobileSelectHandle(v)"
            >
              <div>{{v.phone}}</div>
              <i class="iconfont icon-small-arrow-right" slot="right" />
            </mu-list-item>
          </mu-list>
        </div>
      </div>
    </mu-dialog>

    <!-- 是否在线建档 -->

    <mu-dialog :open="dialogGenerate">
     <div v-if="isCreateOnline">
        <div class="center">
          <p>未查询到患者档案，是否新建档案？</p>
        </div>
        <div class="login center mt20" >
          <mu-flat-button slot="actions" @click="dialogGenerate=false" label="取消" />
          <mu-flat-button slot="actions" primary @click="createHandle" label="在线建档" />
        </div>
     </div>
     <div v-else> 
        <div class="center">
          <p>未查询到就诊人档案，请到医院窗口建档</p>
        </div>
        <div class="login center mt20">
        <mu-flat-button primary slot="actions" @click="dialogGenerate=false" label="确定" />
      </div>
     </div>
    </mu-dialog>
  </div>
</template>

<script>
import {testEmpty} from '@/common/js/util.js'
import {commonAjax, RESTFUL_API, commonAjaxJson} from '@/api/api'
import {HIS_CARD_TYPE, CARD_TYPE2, BIND_CARD_TIPS, BIND_CARD_TIPS2} from '@/api/const'
import Selector from '@/components/Selector'
export default {
  components: {Selector},
  data () {
    return {
      hospitalCode: sessionStorage.getItem("hospitalCode") || "",
      person: JSON.parse(sessionStorage.person || '{}'),
      editFamily: JSON.parse(sessionStorage.editFamily || '{listBasAccountCard: []}'),
      HIS_CARD_TYPE,
      BIND_CARD_TIPS2,
      BIND_CARD_TIPS,
      form: {
        idcard: '',
        cardNumber: '',
        realName: '',
        cardType: '',
        hisCardType: '2',
        mobile: ''
      },
      query: {},
      disabled: false,
      CARD_TYPE: CARD_TYPE2,
      vcodeLabel: '获取验证码',
      vcodeDisabled: false,
      vcode: '',
      listMedicalCard: [],
      selectCardDialog: false,
      checklist: [],
      tipDialog: {
        show: false
      },
      firstComeDialog: false,
      successDialog: false,
      cardList: [],
      dialogMobiles: false,
      mobilesList: [],
      dialogGenerate: false,
      isCreateOnline: false
    }
  },
  mounted () {
    // this.form.cardType = '1'
    let query = this.query = this.editFamily
    this.form.realName = query.realname
    this.form.idcard = query.idcard
    // this.firstComeDialog = true
    this.getCardList()
    this.getSysParameterList()
    this.handleCardChange("2")
  },
  methods: {
    firstConfirm () {
      this.firstComeDialog = false
      this.handleCardChange('2')
    },
    mobileSelectHandle(v) {
      this.form.mobile = v.phone || this.query.mobile;
      this.listMedicalCard = v.listMedicalCard;
      this.dialogMobiles = false;
    },
    selectHandle () {
      this.selectCardDialog = false
    },
    addCards () {
      const len = this.listMedicalCard.length
      if (len === 1) {
        this.addMultiCard()
      } else if (len > 1) {
        this.selectCardDialog = true
      } else {
        // todo
        this.$store.commit('UPDATE_TOAST', {message: '没有找到就诊卡'})
      }
    },
    addMultiCard () {
      // 此处有坑：入参openid为小写， aliUid没问题
      let params = {
        hospitalCode: this.hospitalCode,
        fid: this.query.uid || this.query.id
      }
      if (this.query.relation > 0) {
        params.fid = this.query.id
      }
      if (this.listMedicalCard.length === 1) {
        params.listMedicalCard = this.listMedicalCard
        console.log(params.listMedicalCard)
      } else {
        let temp = []
        this.checklist.forEach(cl => {
          this.listMedicalCard.forEach(lm => {
            if (cl === lm.patientMedicalCardNumber) {
              temp.push(lm)
            }
          })
        })
        params.listMedicalCard = temp
      }
      commonAjaxJson(RESTFUL_API.addCards, params, true).then(res => {
          if (res.data.code == 200) {
          let isMcard = false
          if (this.listMedicalCard.length > 0) {
            let card = this.listMedicalCard[0]
            if (card.cardtype === '5') {
              isMcard = true
            }
          }
          if (isMcard) {
            this.successDialog = true
            return
          }
          this.$store.commit('UPDATE_TOAST', {
            message: '认证成功',
            fn: () => {
              window.history.go(-1)
            }
          })
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.message
          })
        }
      })
    },
    successConfirm () {
      window.history.go(-1)
    },
    checkCode () {
      let query = this.query
      let param = {
        mobile: this.query.mobile,
        code: this.vcode,
        userType: 1
      }
      commonAjax(`${RESTFUL_API.verifyCode}`, param).then(res => {
          if (res.data.code == 200) {
          this.addCards()
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.message
          })
        }
      }).catch(res => {
          this.$store.commit('UPDATE_TOAST', {message: res})
      })
    },
    addcard () {
      if (testEmpty(this.form.cardNumber)) {
        this.$store.commit('UPDATE_TOAST', {message: '请填写您的就诊卡号'})
        return false
      }
      // 此处有坑：入参openid为小写， aliUid没问题
      let params = {
        hospitalCode: this.hospitalCode,
        cardType: this.form.hisCardType,
        cardNum: this.form.cardNumber,
        fid: ''
      }
      if (this.editFamily.relation > 0) {
        params.fid = this.editFamily.id
      }
      commonAjaxJson(`${RESTFUL_API.addCard}`, params, true).then(res => {
          if (res.data.code == 200) {
          this.$store.commit('UPDATE_TOAST', {
            message: '保存成功',
            fn: () => {
              window.history.go(-1)
            }
          })
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.message
          })
        }
      }).catch(res => {
        this.$store.commit('UPDATE_TOAST', {message: res})
      })
    },
    handleCardChange (val) {
      this.form.cardType = val
      if (val == "2") {
        this.getHisPhone().then(res => {
          if (res.data.code == 200) {
            if (res.data.data && res.data.data.length > 1) {
              this.dialogMobiles = true;
              this.mobilesList = res.data.data;
            } else if (res.data.data && res.data.data.length == 1 && res.data.data[0].phone) {
              let d = res.data.data[0];
              this.form.mobile = d.phone
              this.listMedicalCard = d.listMedicalCard;
            }else{
              // 没有查询到预留手机号，在线建档
              this.dialogGenerate = true
            }
          } else {
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.message,
              timeout: 3000
            });
          }
        });
      }
    },
    createHandle (){
      this.$router.push({
        path: "/setting/createOnline"
      })
    },
    handleHisCardChange (val) {
      this.form.hisCardType = val
      if (val == 7 || val == 10) {
        this.form.cardNumber = this.form.idcard;
      } else {
        this.form.cardNumber = '';
      }
    },
    getHisPhone (operationType) {
      let q = this.query
      let params = {
        hospitalCode: this.hospitalCode,
        operationType: operationType || "1"
      }
      if (q.relation > 0) {
        params.fid = q.id
      }
      return commonAjaxJson(RESTFUL_API.getHisPhone, params, true)
    },
    /**
     * 获取系统参数
     */
    getSysParameterList (){
      let params = {
        moduleId: '000000',
        parameterKey: 'ol_archivable'
      }
      commonAjaxJson(RESTFUL_API.getSysParameterList, params, true).then(res =>{
        this.isCreateOnline = res.data.data[0].parameterValue == 1
      })
    },
    getVcode () {
      this.tipDialog.show = false
      this.initTimer()
    },
    __getVcodeBak () {
      this.getHisPhone().then(res => {
        this.tipDialog.show = false
        if (res.data.code === '1') {
          if (res.data.data && (res.data.data.phone !== this.query.mobile)) {
            this.$store.commit('UPDATE_TOAST', {
              message: `此手机号和医院预留的手机号不一致，预留手机号尾号是${res.data.data.phone.slice(-4)}`,
              timeout: 3000}
            )
            return
          }
          this.initTimer()
          const cards = res.data.data.listMedicalCard
          this.listMedicalCard = cards
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.message,
            timeout: 3000
          })
        }
      })
    },
    getCardList () {
      this.cardList = [];
      commonAjaxJson(RESTFUL_API.getCardList, {}, true).then(res => {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            this.cardList.push({
              label: res.data.data[i].cardtypetitle,
              value: res.data.data[i].cardype
            });
          }
        } else {
          this.cardList = HIS_CARD_TYPE;
        }
      })
    },
    initTimer () {
      this.vcodeDisabled = true
      let param = {
        mobile: this.query.mobile
      }
      commonAjax(`${RESTFUL_API.confirmIdByPhone}`, param).then(res => {
        if (res.data.code == 200) {
          this.$store.commit('UPDATE_TOAST', {message: '验证码发送成功'})
          this.timeout()
        } else {
          this.vcodeDisabled = false
          this.$store.commit('UPDATE_TOAST', {message: res.data.message})
        }
      }).catch(() => {
        this.$store.commit('UPDATE_TOAST', {message: '服务错误'})
        this.vcodeDisabled = false
      })
    },
    timeout () {
      let start = 60
      let countDown = () => {
        this.vcodeTimer = setTimeout(() => {
          this.vcodeLabel = (start--) + ''
          countDown()
          if (start <= 0) {
            this.vcodeDisabled = false
            this.vcodeLabel = '获取验证码'
            clearTimeout(this.vcodeTimer)
          }
        }, 1000)
      }
      countDown()
    }
  }
}
</script>
<style lang="less" scoped>

</style>
